const api = require('../../utils/api')
const { ux } = require('../../utils/user-experience')
const app = getApp()

Page({
  data: {
    storeId: null,
    orderType: 'delivery',
    store: {},
    deliveryInfo: {},
    categories: [
      { id: 'all', name: '全部' },
      { id: 'burger', name: '汉堡' },
      { id: 'snack', name: '小食' },
      { id: 'drink', name: '饮品' },
      { id: 'dessert', name: '甜品' }
    ],
    currentCategory: 'all',
    products: [],
    cartTotal: {
      count: 0,
      amount: 0
    },
    scrollHeight: 400,
    loading: false,
    showAddAnimation: false,
    
    // 商品详情弹窗
    showProductModal: false,
    selectedProduct: {},
    modalQuantity: 0,
    modalTotalPrice: '0.00',
    
    // 购物车弹窗
    showCartModal: false
  },

  onLoad(options) {
    // 开始性能监控
    this.performanceMonitor = ux.startPerformanceMonitor('store-detail')
    
    const { id, orderType = 'delivery' } = options
    this.setData({
      storeId: parseInt(id),
      orderType
    })
    
    this.initPage()
    
    // 触觉反馈初始化
    wx.vibrateShort({
      type: 'light'
    });
  },

  onShow() {
    this.updateCartData()
    
    // 添加购物车监听器
    this.cartUpdateListener = (cart) => {
      this.updateCartData()
    }
    app.addCartListener(this.cartUpdateListener)
  },
  
  onHide() {
    // 移除购物车监听器
    if (this.cartUpdateListener) {
      app.removeCartListener(this.cartUpdateListener)
    }
  },

  onReady() {
    // 计算滚动区域高度
    const query = wx.createSelectorQuery()
    query.select('.container').boundingClientRect()
    query.exec((res) => {
      wx.getWindowInfo({
        success: (windowInfo) => {
          const windowHeight = windowInfo.windowHeight
          const containerTop = res[0].top
          const scrollHeight = windowHeight - containerTop - 200 // 减去头部和底部高度
          this.setData({ scrollHeight })
        },
        fail: () => {
          // 降级处理，使用默认高度
          this.setData({ scrollHeight: 400 })
        }
      })
    })
  },

  // 初始化页面
  async initPage() {
    await this.loadStoreDetail()
    await this.loadDeliveryInfo()
    await this.loadProducts()
  },

  // 加载店铺详情
  async loadStoreDetail() {
    const cacheKey = `store_detail_${this.data.storeId}`
    
    try {
      // 检查缓存
      let storeData = ux.getCache(cacheKey, { checkStorage: true })
      
      if (!storeData) {
        ux.showLoading('store_detail', { title: '加载店铺信息...' })
        
        try {
          // 尝试调用真实API
          const result = await api.getStoreDetail(this.data.storeId)
          if (result.code === 200) {
            storeData = result.data
            // 缓存数据
            ux.setCache(cacheKey, storeData, { 
              expire: 10 * 60 * 1000, // 10分钟
              syncToStorage: true 
            })
          } else {
            throw new Error(result.message || '获取店铺信息失败')
          }
        } catch (apiError) {
          console.log('API调用失败，使用模拟数据:', apiError.message)
          
          // API调用失败时使用模拟数据
          storeData = {
            id: this.data.storeId,
            name: '麦当劳(王府井店)',
            description: '经典美式快餐，汉堡薯条',
            avatarUrl: '/images/stores/mcdonalds.jpg',
            coverUrl: '/images/banners/banner1.jpg',
            businessStatus: 'OPEN',
            rating: 4.5,
            reviewCount: 1234,
            monthlySales: 2580,
            deliveryFee: 3,
            minOrderAmount: 20,
            ratingStars: Array(Math.floor(4.5)).fill('★')
          }
          
          // 缓存模拟数据（较短时间）
          ux.setCache(cacheKey, storeData, { 
            expire: 2 * 60 * 1000, // 2分钟
            syncToStorage: false 
          })
        }
        
        ux.hideLoading('store_detail')
      }
      
      this.setData({ store: storeData })
      
      // 设置页面标题
      wx.setNavigationBarTitle({
        title: storeData.name
      })
      
    } catch (error) {
      ux.hideLoading('store_detail')
      ux.handleError(error, '加载店铺详情', {
        showModal: true,
        allowRetry: true,
        onRetry: () => this.loadStoreDetail()
      })
    }
  },

  // 加载配送信息
  async loadDeliveryInfo() {
    if (this.data.orderType !== 'delivery') return
    
    try {
      // 模拟配送信息
      const mockDeliveryInfo = {
        distance: '1.2',
        estimatedDeliveryTime: 25
      }
      
      this.setData({ deliveryInfo: mockDeliveryInfo })
    } catch (error) {
      console.error('加载配送信息失败:', error)
    }
  },

  // 加载商品列表
  async loadProducts() {
    const cacheKey = `store_products_${this.data.storeId}`
    
    this.setData({ loading: true })
    
    try {
      // 检查缓存
      let productsData = ux.getCache(cacheKey, { checkStorage: true })
      
      if (!productsData) {
        try {
          // 尝试调用真实API
          const result = await api.getStoreProducts(this.data.storeId)
          if (result.code === 200) {
            productsData = result.data
            // 缓存数据
            ux.setCache(cacheKey, productsData, { 
              expire: 5 * 60 * 1000, // 5分钟
              syncToStorage: true 
            })
          } else {
            throw new Error(result.message || '获取商品列表失败')
          }
        } catch (apiError) {
          console.log('API调用失败，使用模拟数据:', apiError.message)
          
          // API调用失败时使用模拟数据
          productsData = [
            {
              id: 1,
              name: '巨无霸',
              description: '经典牛肉汉堡',
              price: 25.5,
              originalPrice: 28.0,
              imageUrl: '/images/products/bigmac.jpg',
              categoryId: 'burger',
              monthlySales: 1200,
              recommended: true
            },
            {
              id: 2,
              name: '薯条(大)',
              description: '香脆金黄薯条',
              price: 12.0,
              imageUrl: '/images/products/fries.jpg',
              categoryId: 'snack',
              monthlySales: 800,
              recommended: false
            },
            {
              id: 3,
              name: '可乐(中)',
              description: '冰爽可口可乐',
              price: 8.5,
              imageUrl: '/images/products/coffee.jpg',
              categoryId: 'drink',
              monthlySales: 600,
              recommended: true
            }
          ]
          
          // 缓存模拟数据（较短时间）
          ux.setCache(cacheKey, productsData, { 
            expire: 1 * 60 * 1000, // 1分钟
            syncToStorage: false 
          })
        }
      }
      
      // 推荐商品
      const recommendedProducts = productsData.filter(p => p.recommended)
      
      // 按分类组织商品
      const categoryProducts = this.organizeProdutsByCategory(productsData)
      
      this.setData({
        products: productsData,
        recommendedProducts,
        categoryProducts,
        loading: false
      })
      
      this.updateProductCartQuantity()
      
      // 结束性能监控
      if (this.performanceMonitor) {
        this.performanceMonitor.end()
      }
      
    } catch (error) {
      ux.handleError(error, '加载商品列表', {
        showToast: true
      })
      this.setData({ loading: false })
    }
  },

  // 按分类组织商品
  organizeProdutsByCategory(products) {
    const categoryMap = new Map()
    
    // 创建分类映射
    this.data.categories.forEach(category => {
      categoryMap.set(category.id, {
        categoryId: category.id,
        categoryName: category.name,
        products: []
      })
    })
    
    // 将商品分配到对应分类
    products.forEach(product => {
      if (categoryMap.has(product.categoryId)) {
        categoryMap.get(product.categoryId).products.push(product)
      }
    })
    
    // 转换为数组并过滤空分类
    return Array.from(categoryMap.values()).filter(category => category.products.length > 0)
  },

  // 更新商品购物车数量显示
  updateProductCartQuantity() {
    const cartItems = app.globalData.cart.filter(item => item.storeId === this.data.storeId)
    
    // 更新主商品列表
    const products = this.data.products.map(product => {
      const cartItem = cartItems.find(item => item.productId === product.id)
      return {
        ...product,
        quantity: cartItem ? cartItem.quantity : 0
      }
    })
    
    // 更新推荐商品 - 添加安全检查
    const recommendedProducts = this.data.recommendedProducts && this.data.recommendedProducts.length > 0 
      ? this.data.recommendedProducts.map(product => {
          const cartItem = cartItems.find(item => item.productId === product.id)
          return {
            ...product,
            quantity: cartItem ? cartItem.quantity : 0
          }
        })
      : []
    
    // 更新分类商品 - 添加安全检查
    const categoryProducts = this.data.categoryProducts && this.data.categoryProducts.length > 0
      ? this.data.categoryProducts.map(category => ({
          ...category,
          products: category.products && category.products.length > 0 
            ? category.products.map(product => {
                const cartItem = cartItems.find(item => item.productId === product.id)
                return {
                  ...product,
                  quantity: cartItem ? cartItem.quantity : 0
                }
              })
            : []
        }))
      : []
    
    this.setData({
      products,
      recommendedProducts,
      categoryProducts
    })
  },

  // 更新购物车数据
  updateCartData() {
    const cartItems = app.globalData.cart.filter(item => item.storeId === this.data.storeId)
    const cartTotalQuantity = cartItems.reduce((total, item) => total + item.quantity, 0)
    const cartTotalPrice = cartItems.reduce((total, item) => total + (item.price * item.quantity), 0)
    
    this.setData({
      cartItems,
      cartTotalQuantity,
      cartTotalPrice: cartTotalPrice.toFixed(2)
    })
    
    this.updateProductCartQuantity()
  },

  // 选择分类
  onCategoryChange(e) {
    const categoryId = e.currentTarget.dataset.id;
    this.setData({
      currentCategory: categoryId
    });
    
    // 轻微触觉反馈
    wx.vibrateShort({
      type: 'light'
    });
    
    // 这里可以根据分类筛选商品
    this.filterProductsByCategory(categoryId);
  },

  // 根据分类筛选商品
  filterProductsByCategory(categoryId) {
    // 实际项目中这里会根据分类ID筛选商品
    console.log('筛选分类:', categoryId);
  },

  // 显示商品详情
  showProductDetail(e) {
    const product = e.currentTarget.dataset.product
    const cartItem = this.data.cartItems.find(item => item.productId === product.id)
    const quantity = cartItem ? cartItem.quantity : 0
    
    this.setData({
      showProductModal: true,
      selectedProduct: product,
      modalQuantity: quantity,
      modalTotalPrice: (product.price * quantity).toFixed(2)
    })
  },

  // 隐藏商品详情
  hideProductModal() {
    this.setData({ showProductModal: false })
  },

  // 阻止事件冒泡
  stopPropagation() {
    // 阻止事件冒泡
  },

  // 增加弹窗商品数量
  increaseModalQuantity() {
    const newQuantity = this.data.modalQuantity + 1
    this.setData({
      modalQuantity: newQuantity,
      modalTotalPrice: (this.data.selectedProduct.price * newQuantity).toFixed(2)
    })
  },

  // 减少弹窗商品数量
  decreaseModalQuantity() {
    if (this.data.modalQuantity > 0) {
      const newQuantity = this.data.modalQuantity - 1
      this.setData({
        modalQuantity: newQuantity,
        modalTotalPrice: (this.data.selectedProduct.price * newQuantity).toFixed(2)
      })
    }
  },

  // 将弹窗商品加入购物车
  addModalToCart() {
    const { selectedProduct, modalQuantity } = this.data
    
    if (modalQuantity <= 0) return
    
    // 先清除该商品的购物车记录
    app.removeFromCart(selectedProduct.id, this.data.storeId)
    
    // 重新添加指定数量
    for (let i = 0; i < modalQuantity; i++) {
      app.addToCart(selectedProduct, this.data.storeId)
    }
    
    this.updateCartData()
    this.hideProductModal()
    
    wx.showToast({
      title: '已加入购物车',
      icon: 'success'
    })
  },

  // 添加商品到购物车
  addToCart(e) {
    const productId = parseInt(e.currentTarget.dataset.id);
    const product = this.data.products.find(item => item.id === productId);
    
    if (!product) return;
    
    // 添加到全局购物车
    app.addToCart({
      id: product.id,
      name: product.name,
      price: product.price,
      imageUrl: product.imageUrl
    }, this.data.storeId);
    
    // 更新本页面的购物车数据
    this.updateCartData();
    
    // 🎉 现代化反馈效果
    this.triggerAddFeedback();
    
    // 显示添加成功提示
    wx.showToast({
      title: '已添加到购物车',
      icon: 'success',
      duration: 1500
    });
  },

  // 🎯 减少商品数量
  decreaseQuantity(e) {
    const productId = parseInt(e.currentTarget.dataset.id);
    
    // 从全局购物车中移除一个商品
    app.removeFromCart(productId, this.data.storeId);
    
    // 更新本页面的购物车数据
    this.updateCartData();
    
    // 轻微触觉反馈
    wx.vibrateShort({
      type: 'light'
    });
  },

  // 🎨 现代化添加反馈效果
  triggerAddFeedback() {
    // 1. 触觉反馈
    wx.vibrateShort({
      type: 'medium'
    });
    
    // 2. 视觉反馈 - 添加成功动画
    this.setData({
      showAddAnimation: true
    });
    
    setTimeout(() => {
      this.setData({
        showAddAnimation: false
      });
    }, 800);
  },

  // 计算购物车总计
  calculateCartTotal(products) {
    let count = 0;
    let amount = 0;
    
    products.forEach(product => {
      if (product.quantity > 0) {
        count += product.quantity;
        amount += product.quantity * product.price;
      }
    });
    
    return {
      count,
      amount: amount.toFixed(1)
    };
  },

  // 显示购物车详情
  showCartDetail() {
    this.setData({ showCartModal: true })
  },

  // 隐藏购物车详情
  hideCartModal() {
    this.setData({ showCartModal: false })
  },

  // 前往购物车
  goToCart() {
    // 触觉反馈
    wx.vibrateShort({
      type: 'medium'
    });
    
    wx.navigateTo({
      url: '/pages/cart/cart'
    });
  },

  // 去结算
  goToCheckout() {
    if (this.data.cartItems.length === 0) {
      wx.showToast({
        title: '购物车为空',
        icon: 'none'
      })
      return
    }
    
    if (this.data.cartTotalPrice < this.data.store.minOrderAmount) {
      wx.showToast({
        title: `还差¥${(this.data.store.minOrderAmount - this.data.cartTotalPrice).toFixed(2)}起送`,
        icon: 'none'
      })
      return
    }
    
    wx.navigateTo({
      url: `/pages/order/order?storeId=${this.data.storeId}&orderType=${this.data.orderType}`
    })
  },

  // 页面分享
  onShareAppMessage() {
    return {
      title: `${this.data.store.name} - 美食订餐`,
      path: `/pages/store-detail/store-detail?id=${this.data.storeId}`
    };
  },

  // 分享到朋友圈
  onShareTimeline() {
    return {
      title: `${this.data.store.name} - 美食订餐`
    };
  }
}) 